﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyAlbum.Model;
using MyAlbum.Utility;
using MyAlbum.DataAccess.LinqToSql;


namespace MyAlbum.Data.Linq
{
    public class TagEntryRepository : ITagEntryRepository
    {

        private string _connectionString;
        public TagEntryRepository(string connectionString)
        {
            Assert.IsNotNull(connectionString);
            this._connectionString = connectionString;
        }

        #region ITagEntryRepository Members

        public List<MyAlbum.Model.Tag> GetTags()
        {
            using (var ImagesDB = new DataClasses1DataContext(this._connectionString))
            {
                return ImagesDB.Tags.Select(t => new MyAlbum.Model.Tag()
                {
                    Name = t.Name,
                    Id = t.Id.ToString(),
                    Count = t.Count
                }).ToList();
            }
        }



        public void DeleteTagName(string tagName)
        {
            using (var ImagesDB = new DataClasses1DataContext(this._connectionString))
            {
                var tags = ImagesDB.Tags.Where(s => s.Name == tagName);
                foreach (var item in tags)
                {
                    var relation = ImagesDB.TagEntryRelations.Where(s => s.TagId == item.Id);
                    foreach (var r in relation)
                    {
                        ImagesDB.TagEntryRelations.DeleteOnSubmit(r);
                    }
                    ImagesDB.Tags.DeleteOnSubmit(item);
                }
                ImagesDB.SubmitChanges();
            }
        }

        #endregion
    }
}
